from django.core.validators import ValidationError
from django.utils.datastructures import FileDict
from django.db import connection
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.conf import settings
import comics
import extra

def get_nav():
    result = [["/", "Home"]]
    result += comics.getlinks()
    result += extra.getlinks()
    return result

def ImageSizeValidator(field_data, all_data, height=None, width=None):
    """a blank validator, use django.utils.functional.curry to fix a height and width"""
    from PIL import Image
    from cStringIO import StringIO
    if isinstance(field_data, FileDict):
        trial_image = Image.open(StringIO(field_data['content']))
        image_width, image_height = trial_image.size
        if height and width and height != image_height and width != image_width:
            raise ValidationError("Image must be %d wide by %d tall." % (width, height))
        if height and height != image_height:
            raise ValidationError("Image must be %d pixels tall." % height)
        if width and width != image_width:
            raise ValidationError("Image must be %d pixels wide." % width)

def render_with_requestcontext(template, context, request):
    """
    Returns a HttpResponse whose content is filled with the context given
    as well as a RequestContext filled with the request using the given
    template. How handy!
    It also populates the navbar and sql_debug fields automatically.
    """
    context.update({"nav": get_nav(),"current": request.path})
    if settings.DEBUG:
        context.update({
            "sql": connection.queries,
            "sql_time": sum(float(q["time"]) for q in connection.queries),
        })
    return render_to_response(
        template,
        context, 
        context_instance=RequestContext(request)
    )

# http://www.djangosnippets.org/snippets/727/
import sys
import cProfile
from cStringIO import StringIO

class ProfilerMiddleware(object):
    def process_view(self, request, callback, callback_args, callback_kwargs):
        if settings.DEBUG and 'prof' in request.GET:
            self.profiler = cProfile.Profile()
            args = (request,) + callback_args
            return self.profiler.runcall(callback, *args, **callback_kwargs)

    def process_response(self, request, response):
        if settings.DEBUG and 'prof' in request.GET:
            self.profiler.create_stats()
            out = StringIO()
            old_stdout, sys.stdout = sys.stdout, out
            self.profiler.print_stats(1)
            sys.stdout = old_stdout
            response.content = '<pre>%s</pre>' % out.getvalue()
        return response
